import {Component, OnInit} from '@angular/core';
import {TestRecordService} from './test-record.service';
import {GridComponent} from '@core/grid.component';
import {SearchParams} from '@core/interfaces/table.interface';

@Component({
  selector: 'app-test-record',
  templateUrl: './test-record.component.html',
  styleUrls: ['./test-record.component.less'],
  providers: [TestRecordService]
})
export class TestRecordComponent extends GridComponent implements OnInit {
  isVisible = false;
  details = null;
  searchParams: SearchParams = {
    values: {
      username: '',
      startDate: '',
      endDate: ''
    }
  }

  constructor(private testRecordService: TestRecordService) {
    super(testRecordService);
    /**
     * 列表操作按钮
     */
    this.setGridView('operations', [
      {
        text: '查看',
        key: 'testRecordId',
        event: (id: string) => {
          this._selectDetail(id);
        }
      }
    ]);
  }

  ngOnInit() {
    this.getData();
  }

  getData(event?: number) {
    this.setLoading(true);
    this.testRecordService.queryList(event || this.current, this.pageSize, this.searchParams.values)
      .then((result: any) => {
        if (result) {
          const {content, total} = result;
          this.setTableData(content);
          this.setTotal(total);
        }
        this.setLoading(false);
      });
  }

  handleCancel = (e) => {
    console.log(e);
    this.isVisible = false;
  }

  _startValueChange = () => {
    const {startTime, endTime} = this.searchParams.values;
    if (startTime > endTime) {
      this.searchParams.values.endTime = null;
    }
  }

  _endValueChange = () => {
    const {startTime, endTime} = this.searchParams.values;
    if (startTime > endTime) {
      this.searchParams.values.startTime = null;
    }
  }

  /**
   * 清除搜索框数据
   */
  clearSearchParams() {
    for (const key in this.searchParams.values) {
      this.searchParams.values[key] = '';
    }
  }

  async _selectDetail(id: string) {
    this.details = await this.testRecordService.queryById(id);
    this.isVisible = true;
  }
}
